package com.whosly.mysql.protocol.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author fengyang
 * @date 2023/8/17 下午10:12
 * @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
 */
public class ByteUtils
{

    public static final String toString(byte[] src) {
        return toString(src, null);
    }

    public static final String toString(byte[] src, String charset) {
        if (src == null) {
            return null;
        }

        if (charset == null) {
            return new String(src);
        }

        try {
            return new String(src, charset);
        } catch (UnsupportedEncodingException e) {
            return new String(src);
        }
    }

    public static final byte[] getBytes(String src) {
        return getBytes(src, null);
    }

    public static final byte[] getBytes(String src, String charset) {
        if (src == null) {
            return null;
        }

        if (charset == null) {
            return src.getBytes();
        }

        return src.getBytes(Charset.forName(charset));
    }


    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

}
